package Lee_code;

import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author blh
 * @date 2024年06月24日 16:22
 */
public class Lee_103_624 {
    List<List<Integer>> res = new LinkedList<>();

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(root==null){
            return res;
        }
        // 先从左往右，再从右往左进行下一层遍历
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);
        boolean right2left = true;
        while (!deque.isEmpty()) {
            int dequeSize = deque.size();
            List<Integer> temp = new LinkedList<>();
            for (int i = 0; i < dequeSize; i++) {
                TreeNode curNode;
                if (right2left) {
                    curNode = deque.poll();
                    // 加入左右节点
                    if (curNode.left != null) {
                        deque.offer(curNode.left);
                    }
                    if (curNode.right != null) {
                        deque.offer(curNode.right);
                    }
                } else {
                    curNode = deque.pop();
                    // 加入左右节点
                    if (curNode.left != null) {
                        deque.addFirst(curNode.left);
                    }
                    if (curNode.right != null) {
                        deque.addFirst(curNode.right);
                    }
                }
                temp.add(curNode.val);
            }
            if (!right2left){
                Collections.reverse(temp);
                res.add(temp);
            }
            res.add(temp);
            right2left = !right2left;
        }
        return res;
    }
}
